package com.example.united.jms.publisher;


import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;
import java.util.Scanner;

/**
 * User: AGrankin
 * Date: 07.04.14
 * Time: 17:12
 */
public class JMSPublisher {

    private TopicConnectionFactory topicConnectionFactory;
    private TopicConnection topicConnection;
    private TopicSession topicSession;
    private TopicPublisher topicPublisher;
    private Topic topic;
    private TextMessage msg;
    private static String message;

    protected static InitialContext getInitialContext() throws NamingException {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        env.put(Context.PROVIDER_URL, "t3://10.249.134.252:7001");
        env.put("weblogic.jndi.createIntermediateContexts", "true");
        return new InitialContext(env);
    }

    public void init(Context ctx, String topicName) throws NamingException, JMSException {
        topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("testTopicConnectionFactoryJNDI");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = (Topic) ctx.lookup(topicName);
        topicPublisher = topicSession.createPublisher(topic);
        msg = topicSession.createTextMessage();
        topicConnection.start();
    }

    public void send(String message) throws JMSException {
        msg.setText(message);
        topicPublisher.publish(msg);
        System.out.println("Sending message: " + message);
    }

    public void close() throws JMSException {
        topicPublisher.close();
        topicSession.close();
        topicConnection.close();
        System.out.println("Session closed.");
    }

    public static void main(String... args) throws Exception {
        InitialContext initialContext = getInitialContext();
        JMSPublisher jmsPublisher = new JMSPublisher();
        Scanner in = new Scanner(System.in);

        jmsPublisher.init(initialContext, "testTopicJNDI");
        System.out.println("Please type a message:");

        Thread.sleep(10000);
        message = in.nextLine();
        jmsPublisher.send(message);
        jmsPublisher.close();
    }
}
